package com.yupi.yupicturebackend.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.annotation.DataValidation;
import com.yupi.yupicturebackend.annotation.PerformanceMonitor;
import com.yupi.yupicturebackend.common.BaseResponse;
import com.yupi.yupicturebackend.common.DeleteRequest;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.constant.UserConstant;
import com.yupi.yupicturebackend.manager.auth.annotation.SaSpaceCheckPermission;
import com.yupi.yupicturebackend.manager.auth.model.SpaceUserPermissionConstant;
import com.yupi.yupicturebackend.model.dto.picture.PictureQueryRequest;
import com.yupi.yupicturebackend.model.dto.picture.PictureUploadRequest;
import com.yupi.yupicturebackend.model.entity.Picture;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.vo.PictureVO;
import com.yupi.yupicturebackend.service.PictureService;
import com.yupi.yupicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 图片控制器 - 增强版本
 * 展示新的AOP注解使用
 * 
 * @author yupi
 */
@Slf4j
@RestController
@RequestMapping("/picture/enhanced")
public class PictureEnhancedController {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    /**
     * 上传图片 - 使用性能监控和数据验证注解
     */
    @PostMapping("/upload")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    @PerformanceMonitor(
            value = "图片上传", 
            module = "图片管理", 
            slowThreshold = 3000L, 
            memoryMonitor = true,
            recordArgs = false,
            recordResult = false,
            level = PerformanceMonitor.MonitorLevel.INFO
    )
    @DataValidation(
            requireLogin = true, 
            validateNotNull = true,
            validateNotBlank = true,
            rules = {
                    @DataValidation.ValidationRule(
                            param = "pictureUploadRequest", 
                            type = DataValidation.ValidationType.CUSTOM,
                            message = "上传请求参数不能为空"
                    )
            }
    )
    public BaseResponse<PictureVO> uploadPicture(
            @RequestPart("file") MultipartFile multipartFile,
            PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        
        log.info("用户 {} 成功上传图片: {}", loginUser.getId(), pictureVO.getName());
        
        return ResultUtils.success(pictureVO);
    }

    /**
     * 删除图片 - 使用数据验证注解
     */
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    @PerformanceMonitor(value = "删除图片", module = "图片管理")
    @DataValidation(
            requireLogin = true,
            validateNotNull = true,
            rules = {
                    @DataValidation.ValidationRule(
                            param = "id", 
                            type = DataValidation.ValidationType.RANGE,
                            value = "1,999999999",
                            message = "图片ID必须是有效的正整数"
                    )
            }
    )
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, 
                                             HttpServletRequest request) {
        
        User loginUser = userService.getLoginUser(request);
        pictureService.deletePicture(deleteRequest.getId(), loginUser);
        
        log.info("用户 {} 删除图片: {}", loginUser.getId(), deleteRequest.getId());
        
        return ResultUtils.success(true);
    }
    

    /**
     * 批量删除图片 - 使用数据验证和性能监控
     */
    @PostMapping("/delete/batch")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    @PerformanceMonitor(
            value = "批量删除图片", 
            module = "图片管理", 
            slowThreshold = 5000L,
            memoryMonitor = true,
            level = PerformanceMonitor.MonitorLevel.INFO
    )
    @DataValidation(
            requireLogin = true,
            validateNotNull = true,
            validateNotEmpty = true
    )
    public BaseResponse<Integer> deletePicturesBatch(@RequestBody List<Long> pictureIds, 
                                                   HttpServletRequest request) {
        
        if (pictureIds.size() > 100) {
            throw new RuntimeException("批量删除数量不能超过100");
        }
        
        User loginUser = userService.getLoginUser(request);
        
        int deletedCount = 0;
        for (Long pictureId : pictureIds) {
            try {
                pictureService.deletePicture(pictureId, loginUser);
                deletedCount++;
            } catch (Exception e) {
                log.warn("删除图片失败: {}, 错误: {}", pictureId, e.getMessage());
            }
        }
        
        log.info("用户 {} 批量删除图片，成功删除 {} 张", loginUser.getId(), deletedCount);
        
        return ResultUtils.success(deletedCount);
    }

    /**
     * 获取用户图片统计信息 - 使用性能监控
     */
    @GetMapping("/stats/user")
    @PerformanceMonitor(
            value = "获取用户图片统计", 
            module = "统计分析", 
            slowThreshold = 1000L,
            recordResult = true,
            level = PerformanceMonitor.MonitorLevel.DEBUG
    )
    @DataValidation(requireLogin = true)
    public BaseResponse<Map<String, Object>> getUserPictureStats(HttpServletRequest request) {
        
        User loginUser = userService.getLoginUser(request);
        
        Map<String, Object> stats = Map.of(
                "totalCount", pictureService.countByUserId(loginUser.getId()),
                "publicCount", pictureService.countByUserIdAndSpaceId(loginUser.getId(), null),
                "privateCount", pictureService.countByUserIdAndNotNullSpaceId(loginUser.getId())
        );

        return ResultUtils.success(stats);
    }

    /**
     * 搜索图片 - 使用数据验证和XSS检查
     */
    @PostMapping("/search")
    @PerformanceMonitor(value = "搜索图片", module = "图片搜索", slowThreshold = 2000L)
    @DataValidation(
            validateNotNull = true,
            validateNotBlank = true,
            xssCheck = true,
            sqlInjectionCheck = true,
            rules = {
                    @DataValidation.ValidationRule(
                            param = "keyword", 
                            type = DataValidation.ValidationType.MAX_LENGTH,
                            value = "100",
                            message = "搜索关键词不能超过100个字符"
                    )
            }
    )
    public BaseResponse<Page<PictureVO>> searchPictures(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer pageSize,
            HttpServletRequest request) {
        
        PictureQueryRequest queryRequest = new PictureQueryRequest();
        queryRequest.setSearchText(keyword);
        queryRequest.setCurrent(current);
        queryRequest.setPageSize(pageSize);
        
        Page<Picture> picturePage = pictureService.page(
                new Page<>(current, pageSize),
                pictureService.getQueryWrapper(queryRequest)
        );
        
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
        
        return ResultUtils.success(pictureVOPage);
    }

    /**
     * 验证邮箱格式 - 演示邮箱验证规则
     */
    @PostMapping("/validate/email")
    @DataValidation(
            validateNotNull = true,
            validateNotBlank = true,
            rules = {
                    @DataValidation.ValidationRule(
                            param = "email", 
                            type = DataValidation.ValidationType.EMAIL,
                            message = "邮箱格式不正确"
                    )
            }
    )
    public BaseResponse<String> validateEmail(@RequestParam String email) {
        return ResultUtils.success("邮箱格式验证通过: " + email);
    }

    /**
     * 验证手机号格式 - 演示手机号验证规则
     */
    @PostMapping("/validate/phone")
    @DataValidation(
            validateNotNull = true,
            validateNotBlank = true,
            rules = {
                    @DataValidation.ValidationRule(
                            param = "phone", 
                            type = DataValidation.ValidationType.PHONE,
                            message = "手机号格式不正确"
                    )
            }
    )
    public BaseResponse<String> validatePhone(@RequestParam String phone) {
        return ResultUtils.success("手机号格式验证通过: " + phone);
    }
}
